﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Threading;


namespace UDP_WPF
{
    class Udp
    {
        private delegate void RecDelegate(string str, int ActionStyle); //委托

        //数据
        public UdpClient server;
        public Form1 mainform;
        public bool running;
        public int portsend = 8888;    //发送目标端口
        public int portrec = 9999;    //接受端口
        Thread thread;
        //构造
        public Udp(Form1 fm)
        {
            running = true;
            mainform = fm;
        }

        //接收
        public void rec(int port)
        {
            portrec = port;
            if (null != thread)
            {
                thread.Abort();
                thread = null;
                server = null;
            }
            thread = new Thread(recthread);
            thread.IsBackground = true;
            thread.Start();
        }

        //发送
        public void send(string ip, int port, string content)
        {
            IPAddress ipaddress = IPAddress.Parse(ip);
            if (port != -1)
                portsend = port;
            UdpClient myudpClient = new UdpClient();
            try
            {
                IPEndPoint iep = new IPEndPoint(ipaddress, portsend);
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(content);
                myudpClient.Send(bytes, bytes.Length, iep);
                fresh("发送 - 目标：" + ipaddress + ":" + "" + portsend + "       内容:" + content, 2);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "发送失败");
            }
        }

        //接受数据线程
        public void recthread()
        {
            //获取本地IP
            string ipaddr = "0.0.0.0";
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    ipaddr = _IPAddress.ToString();
                    break;
                }
            }
            fresh("接收开启，本机地址:" + ipaddr + ":" + portrec, 1);
            try
            {
                server = new UdpClient(portrec);    //监听端口  
            }
            catch (SocketException err)
            {
                MessageBox.Show(err.Message, "端口被占用了");
                return;
            }

            IPEndPoint receivepoint = new IPEndPoint(IPAddress.Any, portrec);
            while (running)
            {
                byte[] recbyte = server.Receive(ref receivepoint);  //堵塞接受
                string strData = Encoding.UTF8.GetString(recbyte);  //接受到数据
                fresh("接收 - 来源：" + receivepoint + "       内容:" + strData, 2);
            }
        }

        //刷新界面方法
        public void fresh(string str, int ActionStyle)
        {
            //状态刷新
            if (ActionStyle == 1)
            {
                if (mainform.serverstate.InvokeRequired)//等待异步
                {
                    RecDelegate fc = new RecDelegate(fresh);
                    mainform.Invoke(fc, str, ActionStyle); //通过代理调用刷新方法
                }
                else
                {
                    mainform.serverstate.Text = str;
                }
            }
            //记录刷新
            else if (ActionStyle == 2)
            {
                if (mainform.recmsg.InvokeRequired)//等待异步
                {
                    RecDelegate fc = new RecDelegate(fresh);
                    mainform.Invoke(fc, str, ActionStyle); //通过代理调用刷新方法
                }
                else
                {
                    mainform.recmsg.Text = mainform.recmsg.Text + "\r\n" + str;
                }
            }
        }


    }
}
